<template>
  <div>
    <div class="mb-2">
      <a-radio-group v-model:value="activityCarrier" name="carrierGroup" :disabled="onlyCarrier !== null">
        <a-radio :value="0">券</a-radio>
        <a-radio :value="1">商品</a-radio>
      </a-radio-group>
    </div>
    <div class="flex flex-row items-center">
      <a-input
        class="!w-56 !mr-4 cursor-pointer"
        :value="selectedItem.label"
        readonly
        :placeholder="'请点击选择选择' + (activityCarrier === ActivityCarrier.coupon ? '优惠券' : '商品')"
        @click="showSelect"
      />
      <a-radio-group v-model:value="obtainWays" name="obtainWayGroup">
        <a-radio v-for="el in obtainWayData" :key="el.value" :value="el.value" :disabled="el.disabled">
          {{ el.label }}
          <a-input-number
            v-if="el.value === ObtainWays.buy || el.value === ObtainWays.exchange"
            v-model:value="el.subValue"
            class="!w-28"
            :disabled="obtainWays !== el.value"
            :placeholder="el.value === ObtainWays.buy ? '购买金额' : '兑换积分'"
            @change="consumeValueChange"
          />
        </a-radio>
      </a-radio-group>
    </div>
    <a-modal
      v-model:visible="couponVisible"
      title="选择券"
      :width="800"
      :body-style="{ padding: 0 }"
      @ok="handleCouponSel"
    >
      <TableSelect
        ref="couponSelectIns"
        v-model:value="selCouponIds"
        search-placeholder="搜索券名称"
        search-key="keywords"
        :columns="couponColumns"
        :get-page-url="couponApi.activityCouponPage"
        :field-names="{ value: 'id', label: 'couponsName' }"
        selected-width-cls="w-72"
        single-select
      ></TableSelect>
    </a-modal>
    <a-modal
      v-model:visible="productVisible"
      title="选择商品"
      :width="800"
      :body-style="{ padding: 0 }"
      @ok="handleProductSel"
    >
      <TableSelect
        ref="productSelectIns"
        v-model:value="selProductIds"
        search-placeholder="搜索商品名称或编码"
        search-key="keywords"
        :columns="selProductColumns"
        :get-page-url="pisApi.productFilePage"
        :field-names="{ value: 'id', label: 'name' }"
        selected-width-cls="w-72"
        single-select
      ></TableSelect>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { Api as couponApi } from "/@/api/main/marketing";
import { Api as pisApi } from "/@/api/main/pis";
import {
  AcitivityDefItem,
  ActivityCarrier,
  ActivityType,
  CouponsScope,
  ObtainWays,
} from "/@/api/main/marketing/models";
import { SelectOptionItem } from "/@/types/antd";
import { SelectExpose } from "/@/types/components";
import dayjs from "dayjs";
import { getLabelByValueFromEnum, enumToOptions } from "/@/utils/common";
import { message, TableColumnProps } from "ant-design-vue";
import { ProductFileItem } from "/@/api/main/pis/models";

const props = defineProps<{
  value: AcitivityDefItem["_activityCarrier"];
  model: AcitivityDefItem;
}>();
const emits = defineEmits(["change"]);

const onlyCarrier = ref<ActivityCarrier | null>(null);
const obtainWays = ref(ObtainWays.buy);
const obtainWayData = ref(enumToOptions(ObtainWays, "obtainWays"));
const activityCarrier = ref(ActivityCarrier.coupon);
watch(
  () => props.model.activityType,
  (activityType) => {
    let _onlyCarrier: ActivityCarrier | null = null;
    const disabledObtainWays: ObtainWays[] = [];
    switch (activityType) {
      case ActivityType.chang:
        disabledObtainWays.push(ObtainWays.buy);
        disabledObtainWays.push(ObtainWays.exchange);
        break;
      case ActivityType.jifen:
        disabledObtainWays.push(ObtainWays.give);
        disabledObtainWays.push(ObtainWays.buy);
        break;
      case ActivityType.man:
        disabledObtainWays.push(ObtainWays.buy);
        disabledObtainWays.push(ObtainWays.exchange);
        break;
      case ActivityType.qiang:
        disabledObtainWays.push(ObtainWays.give);
        disabledObtainWays.push(ObtainWays.exchange);
        _onlyCarrier = ActivityCarrier.coupon;
        break;
      case ActivityType.tuan:
        disabledObtainWays.push(ObtainWays.give);
        disabledObtainWays.push(ObtainWays.exchange);
        _onlyCarrier = ActivityCarrier.product;
        break;
    }
    onlyCarrier.value = _onlyCarrier;
    if (_onlyCarrier !== null) {
      activityCarrier.value = _onlyCarrier;
    }
    let firstEnableItem: any = null;
    obtainWayData.value.forEach((el) => {
      if (disabledObtainWays.includes(el.value as ObtainWays)) {
        el.disabled = true;
      } else {
        el.disabled = false;
        if (firstEnableItem === null) {
          firstEnableItem = el;
        }
      }
    });
    if (firstEnableItem) {
      obtainWays.value = firstEnableItem.value as ObtainWays;
    }
  },
  { deep: true, immediate: true }
);
/**
 * input select
 */
const selectedItem = ref<SelectOptionItem>({ label: "", key: "" });
function showSelect() {
  if (activityCarrier.value === ActivityCarrier.coupon) {
    couponVisible.value = true;
  } else {
    productVisible.value = true;
  }
}
/**
 * coupon
 */
const couponVisible = ref(false);
const selCouponIds = ref<string[]>([]);
const couponSelectIns = ref<SelectExpose>();
const couponColumns = ref([
  {
    title: "券名称",
    dataIndex: "couponsName",
  },
  {
    title: "券价值",
    dataIndex: "couponsValue",
  },
  {
    title: "有效期",
    dataIndex: "startPeriod",
    customRender({ record }) {
      if (record.isPermanently) {
        return "长期";
      }
      return dayjs(record.startPeriod).format("YYYY-MM-DD") + "~" + dayjs(record.endPeriod).format("YYYY-MM-DD");
    },
  },
  {
    title: "时段",
    dataIndex: "startTime",
    customRender({ record }) {
      if (record.isAllDay) {
        return "全天";
      }
      return record.startTime + "~" + record.endTime;
    },
  },
  {
    title: "用券范围",
    dataIndex: "couponsScope",
    customRender({ text }) {
      return getLabelByValueFromEnum(text, CouponsScope, "couponsScope");
    },
  },
  {
    title: "是否计算积分",
    dataIndex: "isCalcPoints",
    customRender({ text }) {
      return text ? "√" : "×";
    },
  },
]);
function handleCouponSel() {
  if (selCouponIds.value.length === 0) {
    return message.info("请选择券");
  }
  const items = couponSelectIns.value?.getSelecedItems() as AcitivityDefItem[];
  selectedItem.value = {
    label: items[0].couponsName,
    key: items[0].id,
  };
  couponVisible.value = false;
}
/**
 * product
 */
const productVisible = ref(false);
const selProductIds = ref<number[]>([]);
const productSelectIns = ref<SelectExpose>();
const selProductColumns = ref<TableColumnProps<ProductFileItem>[]>([
  {
    title: "供应商",
    dataIndex: "supplierName",
  },
  {
    title: "品名",
    dataIndex: "name",
  },
  {
    title: "类别",
    dataIndex: "mallClass",
  },
  {
    title: "类型",
    dataIndex: "productType",
  },
  {
    title: "条码",
    dataIndex: "barCode",
  },
  {
    title: "编码",
    dataIndex: "productCode",
  },
]);
function handleProductSel() {
  if (selProductIds.value.length === 0) {
    return message.info("请选择商品");
  }
  const items = productSelectIns.value?.getSelecedItems() as ProductFileItem[];
  selectedItem.value = {
    label: items[0].name,
    key: items[0].id,
  };
  productVisible.value = false;
}
/**
 *
 */
let trigger = true;
watch(activityCarrier, () => {
  if (!trigger) return;
  selectedItem.value = { label: "", key: "" };
});
watch(
  () => props.value,
  (val) => {
    trigger = false;
    if (val) {
      activityCarrier.value = val.activityCarrier;
      obtainWays.value = val.obtainWays;
      const id = val.activityCarrier === ActivityCarrier.coupon ? val.couponsId : val.goodsId;
      const name = val.activityCarrier === ActivityCarrier.coupon ? val.couponsName : val.goodsName;
      // if (selectedItem.value.key !== id || selectedItem.value.label !== name) {
      //   selectedItem.value = { key: id as string, label: (name || id) as string };
      // }
      selectedItem.value.key = id as string;
      selectedItem.value.label = (name || id) as string;
      obtainWayData.value.forEach((el) => {
        if (val.consumeValue && el.value === obtainWays.value) {
          el.subValue = val.consumeValue;
        } else {
          el.subValue = "";
        }
      });
    } else {
      selectedItem.value.label = "";
      selectedItem.value.key = "";
      obtainWayData.value.forEach((el) => {
        el.subValue = "";
      });
      // selectedItem.value = { label: "", key: "" };
    }
    nextTick(() => {
      trigger = true;
    });
  },
  {
    immediate: true,
  }
);
function handleChange(activityCarrier: ActivityCarrier, obtainWays: ObtainWays, selectedItem: SelectOptionItem) {
  // if (!trigger) return;
  if (selectedItem.key) {
    const target = obtainWayData.value.find((el) => el.value === obtainWays);
    // if (target && (target.value === ObtainWays.buy || target.value === ObtainWays.exchange)) {
    //   if (!target.subValue) {
    //     emits("change", null);
    //     return;
    //   }
    // }
    const obj: any = {
      obtainWays,
      activityCarrier,
      couponsId: "",
      consumeValue: target ? target.subValue : null,
    };
    if (activityCarrier === ActivityCarrier.coupon) {
      obj.couponsId = selectedItem.key;
      obj.couponsName = selectedItem.label;
    } else {
      obj.goodsId = selectedItem.key;
      obj.goodsName = selectedItem.label;
    }
    emits("change", obj);
  } else {
    emits("change", null);
  }
}
watch([activityCarrier, obtainWays, selectedItem], ([activityCarrier, obtainWays, selectedItem]) => {
  handleChange(activityCarrier, obtainWays, selectedItem);
});
function consumeValueChange() {
  handleChange(activityCarrier.value, obtainWays.value, selectedItem.value);
}
</script>
